<template>
  <div>
  <el-upload
    ref="uploadRef"
    action=""
    list-type="text"
    :accept="props.upInfo.acceptFile"
    :multiple="props.upInfo.multiple"
    :limit="props.upInfo.limitNum"
    :auto-upload="false"
    :on-exceed="handleExceed"
    :before-upload="beforeUpdata"
    :on-change="handleChange"
    :show-file-list="false"
    :file-list="props.upInfo.upFile"
    :on-success="handleSuccess"
  >
    <template #default> <el-button id="localUpload" plain>本地上传</el-button></template>
  </el-upload>
  <el-dialog 
    custom-class="upLoadImg-dialog-box" 
    v-model="appDialog.visible" 
    :close-on-click-modal="!appDialog.closeModal"
    :width="appDialog.width" 
    destroy-on-close>
    <div class="upLoadImg-content">{{ content }}</div>
    <template #footer>
      <el-button @click="changeImg">{{ appDialog.cancelText }} </el-button>
      <el-button type="primary" @click="confirmImgZip">{{ appDialog.submitText }} </el-button>
    </template>
  </el-dialog>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, watch, computed } from 'vue'
  import { ElForm, ElMessage } from 'element-plus'
  import type { UploadFile } from 'element-plus/es/components/upload/src/upload'
  import { uploadFile2 } from '@/api/common'
  import { getSetionId,getImage_wh, IsNotEmpty, playTime } from '@/utils/utils'
  import ImageCompressor from 'js-image-compressor'
  const uploadRef = ref<any>(null)
  const emit = defineEmits(['submit'])
  const formRef = ref<InstanceType<typeof ElForm>>()
  const props = defineProps(['upInfo', 'remainNum'])

  const zipImgInfo = ref<any>('')
  const content = ref('您上传的图片大小已经超过了最大限制！如果继续，图片将会自动压缩处理。但请注意，压缩后的图片会影响图片的清晰度，请知晓！')
  const appDialog = reactive<any>({
    visible: false,
    title: '提示！',
    width: '400px',
    cancelText: '换一张',
    submitText: '继续'
  })

  const beforeUpdata = async (file: any) => {
    const {acceptFile,limitSize} = props.upInfo
    const is2M = file.size / 1024 / 1024 <= limitSize
    let tips = '图片'
    switch (props.upInfo.type) {
      case 1:
        tips = '图片'
        const { W, H } = await getImage_wh(file)
        let WH = W * H
        let ext = file.name.substring(file.name.lastIndexOf('.'))
        if (acceptFile.indexOf(ext) == -1) {
          ElMessage.warning(`该图片是${ext}格式,请上传${acceptFile}格式图片`)
          handleRemove(file)
          return false
        }
        if (WH > 1555200) {
          // ElMessage.warning(`该图片总像素是${WH},超过最大图片总像素1555200`)
          appDialog.visible = true
          zipImgInfo.value = file
          handleRemove(file)
          return false
        }
        if (H > 10800) {
          appDialog.visible = true
          zipImgInfo.value = file
          handleRemove(file)
          return false
        }
        // if (W > 1440) {
        //   ElMessage.warning(`该图片宽度${W}px,超过最大图片尺寸宽度1440px`)
        //   handleRemove(file)
        //   return
        // }
        // if (H > 1080) {
        //   ElMessage.warning(`该图片高度${H}px,超过最大图片尺寸高度1080px`)
        //   handleRemove(file)
        //   return
        // }
        break
      case 4:
        tips = '语音'
        break
      case 2:
        tips = '视频'
        let extMp4 = file.name.substring(file.name.lastIndexOf('.'))
        if ('.mp4,.MP4'.indexOf(extMp4) == -1) {
          ElMessage.warning(`只能上传Mp4格式`)
          handleRemove(file)
          return false
        }
        const res: any = await playTime(file)
        if (res > 30) {
          ElMessage.warning(`上传的视频不能超过30s`)
          handleRemove(file)
          return false
        }
        break
      case 5:
        tips = '文件'
        break
      default:
        tips = ''
    }
    if (!is2M) {
      if(props.upInfo.type == 1) {
        appDialog.visible = true
        zipImgInfo.value = file
      }else {
        ElMessage.warning(`上传的${tips}最大支持${limitSize}M`)
      }
      handleRemove(file)
      return false
    }
    return is2M
  }
  const handleRemove = (file: UploadFile) => {
    const filePath = file.url
    const i = props.upInfo.upFile.findIndex((x) => x.url === filePath)
    props.upInfo.upFile.splice(i, 1)
    uploadRef.value.handleRemove(file)
    if(props.upInfo.type != 1) {
      emit('submit', props.upInfo.upFile)
    }
    
  }
  const Remove = (file: UploadFile, list: UploadFile[]) => {
    props.upInfo.upFile = list
    emit('submit', list)
  }
  // 上传文件
  const uploadImg = async (file: any) => {
    file = file.raw
    let flag = await beforeUpdata(file)
    if (!flag) return false
    return await uploadFile2({
      file,
      fileName: file.name
    })
  }
  const handleSuccess = (response: any, file: UploadFile, fileList: UploadFile[]) => {}
  // 上传改变
  const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    let existFile = list.slice(0, list.length - 1).find((f) => f.name === file.name)
    if (existFile) {
      ElMessage.error('当前文件已经存在!')
      list.pop()
      return
    }
    try {
      const data: any = await uploadImg(file)
      if(IsNotEmpty(data)) {
        props.upInfo.upFile.push(data)
        if (list.length == props.upInfo.upFile.length) {
          emit('submit', props.upInfo.upFile)
          uploadRef.value.clearFiles()
        }
      }
      
    } catch (e) {
      handleRemove(file)
    }
  }
  const handleExceed = (file: UploadFile, list: UploadFile[]) => {
    ElMessage.warning(`当前限制选择 ${props.upInfo.limitNum} 个文件，本次选择了 ${file.length} 个文件，共选择了 ${file.length + list.length} 个文件`)
    Remove(file, list)
  }

  const changeImg = () => {
    // uploadRef.value.$refs["uploadRef"].handleClick()
    appDialog.visible = false

    const e = document.createEvent("MouseEvents");
    e.initEvent("click", true, true);
    document.getElementById("localUpload")?.dispatchEvent(e);
  }

  const confirmImgZip = () => {
    compressImg(zipImgInfo.value)
  }

  const compressImg = (file: any) => {
    let options = {
      file: file,
      maxWidth: 1440,
      maxHeight: 1080,
      quality: 0.8,
      success: async (res: any) => {
        console.log(res,'1')
        console.log('压缩之后图片尺寸大小: ', res.size);
        let files = new File([res], res.name,{type: res.type, lastModified: res.lastModified});
        files.width = res.width
        files.height = res.height
        files.uid = file.uid
        console.log(files,'files')
        if(res.size/ 1024 / 1024 <= 10) {
            const data: any = await uploadFile2({
              file: files,
              fileName: files.name
            })
            props.upInfo.upFile.push(data)
            emit('submit', props.upInfo.upFile)
            uploadRef.value.clearFiles()
          appDialog.visible = false
        }else {
          compressImg(files)
        }
      }
    }
    new ImageCompressor(options);
  }
</script>
<style lang="scss" scoped>
  .pre_img_box {
    overflow: hidden;
    .pre_image {
      display: block;
      margin: auto;
      max-height: 400px;
    }
  }

  .upLoadImg-dialog-box {
    .upLoadImg-content {
      padding: 50px 30px 24px;
      line-height: 26px;
      text-align: left;
    }
    .img-dialog-footer {
      display: flex;
      justify-content: flex-end;
      border-top: 1px solid #e8e8e8;
      .footer-right {
        margin-left: 10px;
      }
    }
  }
</style>
<style>
  .hide .el-upload--picture-card {
    display: none;
  }
  .upload_icon {
    width: 140px;
    height: 90px;
  }
</style>
